// pages/thief/console/index.js
Page({
  data: {
    // 控制台状态
    consoleStatus: {
      isActive: false,
      currentMission: null,
      scanningProgress: 0,
      detectedTargets: []
    },
    
    // 扫描到的目标
    targets: [
      {
        id: 'partner_001',
        name: '亲爱的TA',
        avatar: '💕',
        distance: '0.1km',
        moodLevel: 75,
        currentMood: '开心',
        moodEmoji: '😊',
        lastSeen: '刚刚',
        stealDifficulty: 'easy',
        availableEmotions: ['开心', '兴奋', '满足', '温暖'],
        isOnline: true,
        relationship: 'partner'
      },
      {
        id: 'friend_001',
        name: '好朋友小李',
        avatar: '👤',
        distance: '2.3km',
        moodLevel: 45,
        currentMood: '焦虑',
        moodEmoji: '😰',
        lastSeen: '5分钟前',
        stealDifficulty: 'medium',
        availableEmotions: ['焦虑', '紧张', '不安'],
        isOnline: true,
        relationship: 'friend'
      },
      {
        id: 'stranger_001',
        name: '神秘用户',
        avatar: '❓',
        distance: '未知',
        moodLevel: 88,
        currentMood: '狂欢',
        moodEmoji: '🎉',
        lastSeen: '1小时前',
        stealDifficulty: 'hard',
        availableEmotions: ['狂欢', '激动', '疯狂'],
        isOnline: false,
        relationship: 'stranger'
      }
    ],
    
    // 偷取历史
    stealHistory: [
      {
        id: 'steal_001',
        targetName: '亲爱的TA',
        emotion: '开心',
        timestamp: Date.now() - 3600000,
        success: true,
        method: 'stealth',
        reward: 50
      },
      {
        id: 'steal_002',
        targetName: '好朋友小李',
        emotion: '焦虑',
        timestamp: Date.now() - 7200000,
        success: false,
        method: 'direct',
        reward: 0
      }
    ],
    
    // 当前选中的目标
    selectedTarget: null,
    
    // 偷取方法
    stealMethods: [
      {
        id: 'stealth',
        name: '隐秘偷取',
        icon: '🥷',
        description: '悄无声息地获取情感',
        successRate: 85,
        duration: 30,
        energyCost: 20,
        unlocked: true
      },
      {
        id: 'direct',
        name: '直接偷取',
        icon: '⚡',
        description: '快速直接的情感获取',
        successRate: 60,
        duration: 10,
        energyCost: 15,
        unlocked: true
      },
      {
        id: 'charm',
        name: '魅力偷取',
        icon: '💫',
        description: '用魅力征服目标',
        successRate: 90,
        duration: 45,
        energyCost: 35,
        unlocked: false,
        unlockCondition: '完成10次成功偷取'
      }
    ],
    
    selectedMethod: null,
    
    // 用户状态
    userStats: {
      energy: 80,
      maxEnergy: 100,
      level: 5,
      experience: 1250,
      maxExperience: 2000,
      totalSteals: 23,
      successRate: 78
    },
    
    // 动画状态
    animations: {},
    isScanning: false,
    showMissionDetail: false,
    currentMissionDetail: null
  },

  onLoad(options) {
    this.initAnimations();
    this.loadUserData();
    this.startAutoScan();
  },

  onShow() {
    this.refreshTargets();
  },

  // 初始化动画
  initAnimations() {
    const animations = {};
    
    // 扫描动画
    animations.scanPulse = wx.createAnimation({
      duration: 1000,
      timingFunction: 'ease-in-out'
    });
    
    // 目标卡片动画
    animations.targetFloat = wx.createAnimation({
      duration: 2000,
      timingFunction: 'ease-in-out'
    });
    
    this.setData({ animations });
  },

  // 加载用户数据
  loadUserData() {
    const savedStats = wx.getStorageSync('user_thief_stats');
    if (savedStats) {
      this.setData({
        userStats: savedStats
      });
    }
  },

  // 开始自动扫描
  startAutoScan() {
    this.setData({ isScanning: true });
    
    const scanAnimation = this.data.animations.scanPulse;
    
    const pulse = () => {
      scanAnimation.scale(1.1).step({ duration: 1000 });
      scanAnimation.scale(1).step({ duration: 1000 });
      
      this.setData({
        'animations.scanPulse': scanAnimation.export()
      });
      
      if (this.data.isScanning) {
        setTimeout(pulse, 2000);
      }
    };
    
    pulse();
    
    // 模拟扫描进度
    this.simulateScanProgress();
  },

  // 模拟扫描进度
  simulateScanProgress() {
    let progress = 0;
    const updateProgress = () => {
      progress += Math.random() * 10;
      if (progress > 100) progress = 100;
      
      this.setData({
        'consoleStatus.scanningProgress': Math.floor(progress)
      });
      
      if (progress < 100 && this.data.isScanning) {
        setTimeout(updateProgress, 500);
      } else {
        this.completeScan();
      }
    };
    
    updateProgress();
  },

  // 完成扫描
  completeScan() {
    this.setData({
      'consoleStatus.detectedTargets': this.data.targets,
      'consoleStatus.scanningProgress': 100
    });
    
    wx.showToast({
      title: `发现${this.data.targets.length}个目标`,
      icon: 'success'
    });
  },

  // 刷新目标列表
  refreshTargets() {
    this.setData({ isScanning: true });
    
    // 模拟网络请求
    setTimeout(() => {
      // 随机更新目标状态
      const updatedTargets = this.data.targets.map(target => ({
        ...target,
        moodLevel: Math.max(10, Math.min(100, target.moodLevel + (Math.random() - 0.5) * 20)),
        lastSeen: target.isOnline ? '刚刚' : `${Math.floor(Math.random() * 60)}分钟前`
      }));
      
      this.setData({
        targets: updatedTargets,
        'consoleStatus.detectedTargets': updatedTargets,
        isScanning: false
      });
    }, 2000);
  },

  // 选择目标
  onSelectTarget(e) {
    const targetId = e.currentTarget.dataset.id;
    const target = this.data.targets.find(t => t.id === targetId);
    
    this.setData({ selectedTarget: target });
    
    // 播放选择音效
    wx.vibrateShort();
  },

  // 选择偷取方法
  onSelectMethod(e) {
    const methodId = e.currentTarget.dataset.id;
    const method = this.data.stealMethods.find(m => m.id === methodId);
    
    if (!method.unlocked) {
      wx.showToast({
        title: method.unlockCondition,
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    if (this.data.userStats.energy < method.energyCost) {
      wx.showToast({
        title: '能量不足',
        icon: 'none'
      });
      return;
    }
    
    this.setData({ selectedMethod: method });
  },

  // 开始偷取任务
  onStartMission() {
    if (!this.data.selectedTarget || !this.data.selectedMethod) {
      wx.showToast({
        title: '请选择目标和方法',
        icon: 'none'
      });
      return;
    }
    
    const mission = {
      id: `mission_${Date.now()}`,
      target: this.data.selectedTarget,
      method: this.data.selectedMethod,
      startTime: Date.now(),
      duration: this.data.selectedMethod.duration * 60 * 1000, // 转换为毫秒
      status: 'active'
    };
    
    this.setData({
      'consoleStatus.isActive': true,
      'consoleStatus.currentMission': mission
    });
    
    // 扣除能量
    this.updateUserStats({
      energy: this.data.userStats.energy - this.data.selectedMethod.energyCost
    });
    
    // 保存任务到本地存储
    wx.setStorageSync('active_mission', mission);
    
    // 开始任务倒计时
    this.startMissionCountdown(mission);
    
    wx.showToast({
      title: '任务已启动',
      icon: 'success'
    });
  },

  // 开始任务倒计时
  startMissionCountdown(mission) {
    const updateCountdown = () => {
      const currentMission = this.data.consoleStatus.currentMission;
      if (!currentMission || currentMission.status !== 'active') return;
      
      const elapsed = Date.now() - mission.startTime;
      const remaining = mission.duration - elapsed;
      
      if (remaining <= 0) {
        this.completeMission(mission);
        return;
      }
      
      const progress = (elapsed / mission.duration) * 100;
      this.setData({
        'consoleStatus.currentMission.progress': Math.floor(progress),
        'consoleStatus.currentMission.timeRemaining': remaining
      });
      
      setTimeout(updateCountdown, 1000);
    };
    
    updateCountdown();
  },

  // 完成任务
  completeMission(mission) {
    const success = Math.random() < (mission.method.successRate / 100);
    
    const result = {
      ...mission,
      status: 'completed',
      success,
      completedAt: Date.now(),
      reward: success ? 50 : 10
    };
    
    this.setData({
      'consoleStatus.isActive': false,
      'consoleStatus.currentMission': null
    });
    
    // 更新用户统计
    this.updateUserStats({
      experience: this.data.userStats.experience + result.reward,
      totalSteals: this.data.userStats.totalSteals + 1
    });
    
    // 添加到历史记录
    const newHistory = [{
      id: result.id,
      targetName: result.target.name,
      emotion: result.target.currentMood,
      timestamp: result.completedAt,
      success: result.success,
      method: result.method.id,
      reward: result.reward
    }, ...this.data.stealHistory.slice(0, 9)];
    
    this.setData({ stealHistory: newHistory });
    
    // 清除本地存储
    wx.removeStorageSync('active_mission');
    
    // 显示结果
    this.showMissionResult(result);
  },

  // 显示任务结果
  showMissionResult(result) {
    const title = result.success ? '偷取成功！' : '偷取失败';
    const content = result.success 
      ? `成功偷取了${result.target.name}的${result.target.currentMood}情感！获得${result.reward}经验值。`
      : `偷取失败了，但获得了${result.reward}经验值。不要灰心，继续努力！`;
    
    wx.showModal({
      title,
      content,
      showCancel: false,
      confirmText: '知道了',
      success: () => {
        if (result.success) {
          this.celebrateSuccess();
        }
      }
    });
  },

  // 庆祝成功
  celebrateSuccess() {
    wx.showToast({
      title: '太棒了！',
      icon: 'success'
    });
    
    // 震动反馈
    wx.vibrateShort();
  },

  // 更新用户统计
  updateUserStats(updates) {
    const newStats = { ...this.data.userStats, ...updates };
    
    // 检查升级
    if (newStats.experience >= newStats.maxExperience) {
      newStats.level += 1;
      newStats.experience = newStats.experience - newStats.maxExperience;
      newStats.maxExperience = Math.floor(newStats.maxExperience * 1.5);
      newStats.maxEnergy += 10;
      
      wx.showToast({
        title: `升级到${newStats.level}级！`,
        icon: 'success'
      });
    }
    
    this.setData({ userStats: newStats });
    
    // 保存到本地存储
    wx.setStorageSync('user_thief_stats', newStats);
  },

  // 查看任务详情
  onViewMissionDetail(e) {
    const missionId = e.currentTarget.dataset.id;
    const mission = this.data.stealHistory.find(m => m.id === missionId);
    
    this.setData({
      currentMissionDetail: mission,
      showMissionDetail: true
    });
  },

  // 关闭任务详情
  onCloseMissionDetail() {
    this.setData({
      showMissionDetail: false,
      currentMissionDetail: null
    });
  },

  // 停止当前任务
  onStopMission() {
    wx.showModal({
      title: '确认停止',
      content: '确定要停止当前任务吗？已消耗的能量不会返还。',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            'consoleStatus.isActive': false,
            'consoleStatus.currentMission': null
          });
          
          wx.removeStorageSync('active_mission');
          
          wx.showToast({
            title: '任务已停止',
            icon: 'success'
          });
        }
      }
    });
  },

  // 恢复能量
  onRestoreEnergy() {
    if (this.data.userStats.energy >= this.data.userStats.maxEnergy) {
      wx.showToast({
        title: '能量已满',
        icon: 'none'
      });
      return;
    }
    
    wx.showModal({
      title: '恢复能量',
      content: '观看广告可以恢复20点能量，是否继续？',
      success: (res) => {
        if (res.confirm) {
          // 模拟观看广告
          wx.showLoading({ title: '加载中...' });
          
          setTimeout(() => {
            wx.hideLoading();
            
            const newEnergy = Math.min(
              this.data.userStats.maxEnergy,
              this.data.userStats.energy + 20
            );
            
            this.updateUserStats({ energy: newEnergy });
            
            wx.showToast({
              title: '能量恢复成功',
              icon: 'success'
            });
          }, 2000);
        }
      }
    });
  },

  // 手动扫描
  onManualScan() {
    if (this.data.isScanning) {
      wx.showToast({
        title: '正在扫描中',
        icon: 'none'
      });
      return;
    }
    
    this.setData({
      'consoleStatus.scanningProgress': 0,
      'consoleStatus.detectedTargets': []
    });
    
    this.startAutoScan();
  },

  // 分享成就
  onShareAchievement() {
    return {
      title: `我在心情小偷中心达到了${this.data.userStats.level}级！`,
      path: '/pages/thief/console/index',
      imageUrl: '/images/share-achievement.png'
    };
  }
});